//
// Created by bxw57 on 2024/6/6.
//
#include <iostream>
#include <winsock.h>
#include <io.h>

using namespace std;

class TcpClient {
public:
    int m_clientFd;
    string m_ip;
    unsigned short m_port;
    TcpClient() : m_clientFd(-1){}
    bool connect(const string &in_ip, const unsigned short &in_port) {
        //创建客户端socket
        if (m_clientFd != -1)
            return false;
        m_ip = in_ip;
        m_port = in_port;
        if ((m_clientFd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
            return false; //socket 申请失败，编码fd已满

        //向服务器发起连接请求
        struct sockaddr_in servAddr; //存ip与post的结构体
        memset(&servAddr, 0, sizeof(servAddr));
        servAddr.sin_family = AF_INET;
        servAddr.sin_port = htons(m_port);
        struct hostent* h;
        if ((h = gethostbyname(m_ip.c_str())) == nullptr) {
            close(m_clientFd);
            m_clientFd = -1;
            return false;
        }
        memcpy(&servAddr.sin_addr, h->h_addr, h->h_length);
        if (::connect(m_clientFd, (struct sockaddr*)&servAddr, sizeof(servAddr)) == -1){
            close(m_clientFd);
            m_clientFd = -1;
            return false;
        }

        return true;
    }

    ~TcpClient(){}
};